package com.hopes.bizz.risk.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hopes.bizz.common.core.annotation.TenantJobRun;
import com.hopes.bizz.risk.common.constant.IntegralEventEnum;
import com.hopes.bizz.risk.common.constant.RiskDicConstant;
import com.hopes.bizz.risk.control.entity.RiskMeasureTaskRecordEntity;
import com.hopes.bizz.risk.control.service.RiskMeasureTaskRecordService;
import com.hopes.bizz.risk.integral.bo.IntegralEvent;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/7/21 15:55
 * @Description: 隐患排查任务定时任务
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RiskHiddenCheckExpireService{

    private final RiskMeasureTaskRecordService riskMeasureTaskRecordService;

    private final ApplicationEventPublisher eventPublisher;

    @TenantJobRun
    @XxlJob("riskHiddenCheckExpireJobHandler")
    public void riskHiddenCheckExpireJobHandler() {
        final Calendar instance = Calendar.getInstance();
        LambdaQueryWrapper<RiskMeasureTaskRecordEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RiskMeasureTaskRecordEntity::getTaskStatus, RiskDicConstant.HIDDEN_CHECK_TASK_STATUS_NOT_FINISH);
        wrapper.le(RiskMeasureTaskRecordEntity::getTaskDeadlineTime, instance.getTime());
        List<RiskMeasureTaskRecordEntity> list = riskMeasureTaskRecordService.list(wrapper);
        for (RiskMeasureTaskRecordEntity record : list) {
            record.setTaskStatus(RiskDicConstant.HIDDEN_CHECK_TASK_STATUS_EXPIRE);
            record.setTaskHandleTime(new Date());
            riskMeasureTaskRecordService.updateById(record);
            // 统计积分
            IntegralEvent integralEvent = new IntegralEvent();
            integralEvent.setBusinessId(record.getId());
            integralEvent.setModule(IntegralEventEnum.risk_control_integral);
            eventPublisher.publishEvent(integralEvent);
        }
    }
}
